<template>
  <view class="notification-list">
    <!-- 导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <view slot="content" class="nav-title">消息通知</view>
    </cu-custom>

    <!-- 通知列表内容 -->
    <view class="notification-content">
      <!-- 筛选标签 -->
      <view class="filter-tabs">
        <view
          v-for="tab in filterTabs"
          :key="tab.key"
          :class="['tab-item', currentTab === tab.key ? 'active' : '']"
          @tap="switchTab(tab.key)"
        >
          {{ tab.label }}
        </view>
      </view>

      <!-- 通知列表 -->
      <view class="notification-items">
        <view v-if="notifications.length === 0" class="empty-state">
          <text class="cuIcon-notification text-xxl text-gray"></text>
          <view class="empty-text">暂无通知消息</view>
        </view>

        <view v-else>
          <view
            v-for="notification in notifications"
            :key="notification.id"
            :class="[
              'notification-item',
              notification.readFlag === '0' ? 'unread' : '',
            ]"
            @tap="handleNotificationTap(notification)"
          >
            <view class="notification-card">
              <view class="card-header">
                <view
                  :class="[
                    'notification-icon',
                    getNotificationIconClass(notification.priority),
                  ]"
                ></view>
                <view class="notification-info">
                  <view class="notification-title">{{
                    notification.titile
                  }}</view>
                  <view class="notification-time">{{
                    formatTime(notification.sendTime)
                  }}</view>
                </view>
                <view
                  v-if="notification.readFlag === '0'"
                  class="unread-dot"
                ></view>
              </view>

              <view class="notification-content-preview">
                {{ getPlainTextContent(notification.msgContent) }}
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { announcement } from "@/api/sys/announcement.js";
import { USER_INFO } from "@/common/util/constants.js";

export default {
  name: "NotificationList",

  data() {
    return {
      currentTab: "all",
      filterTabs: [
        { key: "all", label: "全部" },
        { key: "unread", label: "未读" },
        { key: "read", label: "已读" },
      ],
      notifications: [],
      loading: false,
    };
  },

  onLoad() {
    this.loadNotifications();
  },

  onShow() {
    this.loadNotifications();
  },

  methods: {
    // 切换筛选标签
    switchTab(tabKey) {
      this.currentTab = tabKey;
      this.loadNotifications();
    },

    // 加载通知列表
    async loadNotifications() {
      try {
        this.loading = true;

        const userInfo = uni.getStorageSync(USER_INFO);
        if (!userInfo || !userInfo.id) {
          console.warn("用户信息不完整，无法加载通知");
          return;
        }

        const params = {
          pageNo: 1,
          pageSize: 20,
        };

        // 只有在非"全部"标签时才添加readFlag参数
        if (this.currentTab !== "all") {
          params.readFlag = this.currentTab === "unread" ? "0" : "1";
        }

        console.log("API请求参数:", params);
        const response = await announcement.getMyAnnouncementSend(params);

        if (response && response.data.success) {
          const notificationData =
            response.data.result.records || response.result || [];
          this.notifications = notificationData.map((item) => ({
            id: item.id,
            titile: item.titile || "无标题",
            msgContent: item.msgContent || "",
            sendTime: item.sendTime,
            priority: item.priority || "M",
            readFlag: item.readFlag,
            anntId: item.anntId,
          }));
        } else {
          console.error("获取通知失败:", response?.message);
        }
      } catch (error) {
        console.error("加载通知失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    // 处理通知点击
    async handleNotificationTap(notification) {
      try {
        // 如果未读，标记为已读
        if (notification.readFlag === "0") {
          await this.markNotificationAsRead(notification.id);
          // 如果当前在"未读"标签页，重新加载列表以更新显示
          if (this.currentTab === "unread") {
            await this.loadNotifications();
          }
        }

        // 跳转到详情页
        uni.navigateTo({
          url: `/pages/system/notification/detail?id=${
            notification.anntId
          }&title=${encodeURIComponent(
            notification.titile
          )}&content=${encodeURIComponent(
            notification.msgContent
          )}&time=${encodeURIComponent(notification.sendTime)}&priority=${
            notification.priority
          }`,
        });
      } catch (error) {
        console.error("处理通知点击失败:", error);
      }
    },

    // 标记通知为已读
    async markNotificationAsRead(notificationId) {
      try {
        const response = await announcement.markAsRead({
          anntId: notificationId,
          readFlag: "1",
        });

        if (response && response.success) {
          // 更新本地状态
          const notification = this.notifications.find(
            (n) => n.id === notificationId
          );
          if (notification) {
            notification.readFlag = "1";
          }
        } else {
          console.error("标记通知已读失败:", response?.message);
        }
      } catch (error) {
        console.error("标记通知已读失败:", error);
      }
    },

    // 获取通知图标样式类
    getNotificationIconClass(priority) {
      const iconMap = {
        H: "cuIcon-warn text-red",
        M: "cuIcon-notification text-orange",
        L: "cuIcon-info text-blue",
      };
      return iconMap[priority] || "cuIcon-notification text-blue";
    },

    // 从HTML内容中提取纯文本
    getPlainTextContent(htmlContent) {
      if (!htmlContent) return "";
      return htmlContent
        .replace(/<[^>]*>/g, "")
        .replace(/\s+/g, " ")
        .trim();
    },

    // 格式化时间
    formatTime(dateTime) {
      if (!dateTime) return "";

      const now = new Date();
      const notificationDate = new Date(dateTime);
      const diffMs = now - notificationDate;
      const diffMins = Math.floor(diffMs / (1000 * 60));
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

      if (diffMins < 1) return "刚刚";
      if (diffMins < 60) return `${diffMins}分钟前`;
      if (diffHours < 24) return `${diffHours}小时前`;
      if (diffDays < 7) return `${diffDays}天前`;

      return `${notificationDate.getMonth() + 1}/${notificationDate.getDate()}`;
    },
  },
};
</script>

<style lang="scss" scoped>
.notification-list {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: white;
}

.notification-content {
  padding: 40rpx 32rpx;
}

.filter-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50rpx;
  padding: 8rpx;
  margin-bottom: 32rpx;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 16rpx 24rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;

    &.active {
      background: #667eea;
      color: white;
      font-weight: bold;
    }
  }
}

.notification-items {
  .empty-state {
    text-align: center;
    padding: 120rpx 40rpx;
    color: rgba(255, 255, 255, 0.7);

    .cuIcon-notification {
      font-size: 120rpx;
      margin-bottom: 24rpx;
    }

    .empty-text {
      font-size: 32rpx;
    }
  }

  .notification-item {
    margin-bottom: 24rpx;

    &.unread {
      .notification-card {
        border-left: 6rpx solid #52c41a;
        background: rgba(255, 255, 255, 0.98);
      }
    }

    .notification-card {
      background: rgba(255, 255, 255, 0.9);
      border-radius: 24rpx;
      padding: 32rpx;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      &:active {
        transform: scale(0.98);
        background: rgba(255, 255, 255, 0.95);
      }

      .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        position: relative;

        .notification-icon {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          background: #f5f5f5;
          font-size: 28rpx;
          margin-right: 24rpx;
        }

        .notification-info {
          flex: 1;

          .notification-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 8rpx;
            line-height: 1.4;
          }

          .notification-time {
            font-size: 24rpx;
            color: #999;
          }
        }

        .unread-dot {
          width: 16rpx;
          height: 16rpx;
          background: #52c41a;
          border-radius: 50%;
          position: absolute;
          top: 0;
          right: 0;
        }
      }

      .notification-content-preview {
        font-size: 28rpx;
        color: #666;
        line-height: 1.6;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
